package com.nulldev.util.networking.misc.tls;

import com.nulldev.util.JVM.Arguments;
import com.nulldev.util.JVM.Arguments.ArgumentInit;
import com.nulldev.util.JVM.Arguments.ParsedArguments;
import com.nulldev.util.JVM.JVM;
import com.nulldev.util.JVM.arguments.ArgumentWithValue.BooleanArgument;
import com.nulldev.util.JVM.arguments.ArgumentWithValue.StringArgument;
import com.nulldev.util.io.FastIO.FastIO;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.networking.misc.TLSUtil;

public class TLSPEMTests {

	public static void main(String[] args) {
		final StringArgument PEM_PATH = new StringArgument("--pem-path", "The path to the test PEM file.", "A valid file path", false);
		final StringArgument PRIV_KEY_PEM_PATH = new StringArgument("--priv-pem-path", "The path to the test private key PEM file.", "A valid file path",
				false);
		final BooleanArgument TREAT_PRIVATE_KEY_AS_ECDSA = new BooleanArgument("--priv-key-ec", "Tells the cert manager to load a EC private key.",
				"boolean value", true);
		Arguments.argumentInit(new ArgumentInit() {

			@Override
			public void onInit(Arguments args) {
				args.addArgument(PEM_PATH);
				args.addArgument(PRIV_KEY_PEM_PATH);
				args.addArgument(TREAT_PRIVATE_KEY_AS_ECDSA);
			}
		});
		Arguments.setup(args);
		final ParsedArguments pa = Arguments.awaitGet();
		final boolean ecdsaKey = pa.has(TREAT_PRIVATE_KEY_AS_ECDSA) && pa.getValue(TREAT_PRIVATE_KEY_AS_ECDSA);
		if (!pa.has(PEM_PATH)) {
			JVM.println("ERROR: PEM_PATH is missing!");
			FastIO.get().flush();
			JVM.exit();
			return;
		}
		if (!pa.has(PRIV_KEY_PEM_PATH)) {
			JVM.println("ERROR: PRIV_KEY_PEM_PATH is missing!");
			FastIO.get().flush();
			JVM.exit();
			return;
		}
		final String path = pa.getValue(PEM_PATH);
		if (!FileUtil.isFile(path)) {
			JVM.println("ERROR: File not found!");
			FastIO.get().flush();
			JVM.exit();
			return;
		}
		final String keyPath = pa.getValue(PRIV_KEY_PEM_PATH);
		if (!FileUtil.isFile(keyPath)) {
			JVM.println("ERROR: File not found!");
			FastIO.get().flush();
			JVM.exit();
			return;
		}
		try {
			JVM.println(TLSUtil.getKeyManagers(path, keyPath, ecdsaKey));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
